package com.qs.eggs.user;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imageutils.BitmapUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.qs.eggs.Constants;
import com.qs.eggs.MainActivity;
import com.qs.eggs.R;
import com.qs.eggs.account.LoginActivity;
import com.qs.eggs.bean.User;
import com.qs.eggs.utils.Utils;
import com.qs.eggs.view.activity.UpdInfoActivity;
import com.qs.eggs.view.fragment.MineFragment;
import com.qs.eggs.view.prodetail.activity.ProDetailActivity;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Response;

public class UserInfoActivity extends Activity implements View.OnClickListener{
    private Toolbar back;
    private RelativeLayout touxiang;
    private TextView zhanghu,name,phone,jifen,changepwd;
    private Button exit;
    private String custname,xingming,imageUrl,number,score;
    private SimpleDraweeView draweeView;
    public static Activity instance;
    protected static final int PHOTO_REQUEST = 1;
    protected static final int CAMERA_REQUEST = 2;
    protected static final int PHOTO_CLIP = 3;

    /* 头像名称 */
    private static final String PHOTO_FILE_NAME = "PHOTOIMAGE_ANSWER.jpg";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance=this;
        setContentView(R.layout.activity_user_info);
        initView();
    }
    private void initView(){
       touxiang=(RelativeLayout)findViewById(R.id.rl_touxiang);
        draweeView=(SimpleDraweeView)findViewById(R.id.touxiang);
        zhanghu=(TextView)findViewById(R.id.zhanghu);
        name=(TextView)findViewById(R.id.name);
        phone=(TextView)findViewById(R.id.phone);
        jifen=(TextView)findViewById(R.id.jifen);
        changepwd=(TextView)findViewById(R.id.changepwd);
        exit=(Button)findViewById(R.id.exit);
        back=(Toolbar)findViewById(R.id.toolbar);
        touxiang.setOnClickListener(this);
        zhanghu.setOnClickListener(this);
        name.setOnClickListener(this);
        phone.setOnClickListener(this);
        jifen.setOnClickListener(this);
        changepwd.setOnClickListener(this);
        exit.setOnClickListener(this);
        back.setOnClickListener(this);
        getPersonalInfo();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar:
               UserInfoActivity.this.finish();
                break;
            case R.id.rl_touxiang:
                showChoosePicDialog();
                break;
            case R.id.zhanghu:
                Intent intent4=new Intent(UserInfoActivity.this, UpdInfoActivity.class);
                intent4.putExtra("flag","4");
                startActivity(intent4);
                break;
            case R.id.name:
                Intent intent1=new Intent(UserInfoActivity.this, UpdInfoActivity.class);
                intent1.putExtra("flag","1");
                startActivity(intent1);
                break;
            case R.id.phone:
                Intent intent2=new Intent(UserInfoActivity.this, UpdInfoActivity.class);
                intent2.putExtra("flag","2");
                startActivity(intent2);
                break;
            case R.id.changepwd:
                Intent intent3=new Intent(UserInfoActivity.this, UpdInfoActivity.class);
                intent3.putExtra("flag","3");
                startActivity(intent3);
                break;
            case R.id.exit:
                outLogin();
                break;
        }
    }
    //获取用户信息
    private void getPersonalInfo(){
        OkGo.post(Constants.URL_BASE+"personal?action=getPersonalInfo")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                      System.out.print("个人信息=="+s);
                        try {
                            JSONArray jsonArray = new JSONArray(s);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                custname=jsonArray.getJSONObject(i).getString("accountname");
                                xingming=jsonArray.getJSONObject(i).getString("name");
                                number=jsonArray.getJSONObject(i).getString("phone");
                                score=jsonArray.getJSONObject(i).getString("score");
                                imageUrl= Constants.URL_BASE+jsonArray.getJSONObject(i).getString("folder")+"/"
                                        +jsonArray.getJSONObject(i).getString("autoname");
                                Picasso.with(UserInfoActivity.this).load(imageUrl).placeholder(R.mipmap.icon_personimg).error(R.mipmap.icon_personimg).into(draweeView);
                                zhanghu.setText(custname);
                                name.setText(xingming);
                                phone.setText(number);
                                jifen.setText(score);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
    //退出登录
    private void outLogin(){
        new AlertDialog.Builder(UserInfoActivity.this)
                .setTitle("退出")
                .setMessage("确定退出登陆吗")
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,int which) {
                                OkGo.post(Constants.URL_BASE+"mallLogin?action=exiteMallLogin ")
                                        .execute(new StringCallback() {
                                            @Override
                                            public void onSuccess(String s, Call call, Response response) {
                                                System.out.print("退出登录=="+s);
                                                if (s.equals("\"true\"")){
                                                    UserInfoActivity.this.finish();
                                                    Intent intent=new Intent(UserInfoActivity.this, LoginActivity.class);
                                                    startActivity(intent);
                                                }
                                            }
                                        });
                            }
                        })
                .setNegativeButton("取消",new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog,int which) {
                    }
                }).setCancelable(false).show();

    }
    /**
     * 显示修改头像的对话框
     */
    protected void showChoosePicDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("设置头像");
        String[] items = { "选择本地照片", "拍照" };
        builder.setNegativeButton("取消", null);
        builder.setItems(items, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0: // 选择本地照片
                        Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                        startActivityForResult(intent, PHOTO_REQUEST);
                        break;
                    case 1: // 拍照
                        Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent1.putExtra("camerasensortype", 2);//调用前置摄像头
                        intent1.putExtra("autofocus", true);//进行自动对焦操作
                        intent1.putExtra("fullScreen", false);//设置全屏
                        intent1.putExtra("showActionIcons", false);
                        intent1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
                        startActivityForResult(intent1, CAMERA_REQUEST);
                        break;
                }
            }
        });
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CAMERA_REQUEST:
                switch (resultCode) {
                    case -1:// -1表示拍照成功
                        File file = new File(Environment.getExternalStorageDirectory() + "/"+PHOTO_FILE_NAME);
                        if (file.exists()) {
                            photoClip(Uri.fromFile(file));
                        }

                        break;
                    default:
                        break;
                }
                break;
            case PHOTO_REQUEST:
                if (data != null) {
                    photoClip(data.getData());
                }
                break;
            case PHOTO_CLIP:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        Bitmap photo = extras.getParcelable("data");
                        //转成圆形图片
                        photo=toRoundBitmap(photo);
                       draweeView.setImageBitmap(photo);
                        //将bitmap转换为File
                        Bitmap.CompressFormat format = Bitmap.CompressFormat.JPEG;
                        int quality = 100;
                        OutputStream stream = null;
                        try {
                            stream = new FileOutputStream(Environment.getExternalStorageDirectory() + "/"+PHOTO_FILE_NAME);
                        } catch (FileNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        photo.compress(format, quality, stream);

                        //异步上传文件
                        uploadFile();
                    }
                }
                break;
        }

    }

    private void photoClip(Uri uri) {
        // 调用系统中自带的图片剪裁
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_CLIP);
    }

    /**
     * 转换图片成圆形
     *
     * @param bitmap
     *            传入Bitmap对象
     * @return
     */
    public Bitmap toRoundBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
        if (width <= height) {
            roundPx = width / 2;
            top = 0;
            bottom = width;
            left = 0;
            right = width;
            height = width;
            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;
            float clip = (width - height) / 2;
            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;
            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }
        Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);
        final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);
        final RectF rectF = new RectF(dst);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);
        return output;
    }
    //上传
    public void uploadFile() {
        String filePath = Environment.getExternalStorageDirectory() + "/"+PHOTO_FILE_NAME;
        OkGo.post(Constants.URL_BASE+"personal?action=uploadCustomerImage")
                .params("file",new File(filePath),filePath)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        System.out.print("上传头像=="+s);
                        if (s.equals("\"true\"")){
                            Toast.makeText(UserInfoActivity.this,"头像上传成功",Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(UserInfoActivity.this,"头像上传失败",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

}
